<?php

namespace app\model;

use think\facade\Log;

class Dept extends BaseModel
{
    /**
     * 获取部门列表
     * @return array
     */
    public function getDeptList()
    {
        try {

            $list = $this->select();
        } catch (\Exception $e) {
            Log::error('获取部门列表失败: ' . $e->getMessage() . PHP_EOL  . $e->getTraceAsString());
            return dataReturn(-1, $e->getMessage());
        }

        return dataReturn(0, 'success', $list);
    }

    /**
     * 添加部门
     * @return array
     */
    public function addDept($param)
    {
        try {

            $has = $this->where('name', $param['name'])->find();
            if (!empty($has)) {
                return dataReturn(-2, '该部门已经存在');
            }

            $param['create_time'] = date('Y-m-d H:i:s');
            $this->insert($param);
        } catch (\Exception $e) {
            Log::error('添加部门失败: ' . $e->getMessage() . PHP_EOL  . $e->getTraceAsString());
            return dataReturn(-1, $e->getMessage());
        }

        return dataReturn(0, '添加成功');
    }

    /**
     * 编辑部门
     * @return array
     */
    public function editDept($param)
    {
        try {

            $has = $this->where('name', $param['name'])->where('id', '<>', $param['id'])->find();
            if (!empty($has)) {
                return dataReturn(-2, '该部门已经存在');
            }

            $param['update_time'] = date('Y-m-d H:i:s');
            $this->where('id', $param['id'])->update($param);
        } catch (\Exception $e) {
            Log::error('编辑部门失败: ' . $e->getMessage() . PHP_EOL  . $e->getTraceAsString());
            return dataReturn(-1, $e->getMessage());
        }

        return dataReturn(0, '编辑成功');
    }

    /**
     * 删除部门
     * @param $deptId
     * @return array
     */
    public function delDeptById($deptId)
    {
        try {

            $this->where('id', $deptId)->delete();
        } catch (\Exception $e) {
            Log::error('删除部门失败: ' . $e->getMessage() . PHP_EOL  . $e->getTraceAsString());
            return dataReturn(-1, $e->getMessage());
        }

        return dataReturn(0, '编辑成功');
    }

    /**
     * 获取子部门
     * @param $deptId
     * @return array
     */
    public function getSubDept($deptId)
    {
        try {

            $info = $this->where('pid', $deptId)->find();
        } catch (\Exception $e) {
            Log::error('获取子部门失败: ' . $e->getMessage() . PHP_EOL  . $e->getTraceAsString());
            return dataReturn(-1, $e->getMessage());
        }

        return dataReturn(0, 'success', $info);
    }
}